package com.example.a79273.shandianban.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.a79273.shandianban.LoginActivity;
import com.example.a79273.shandianban.OrderActivity;
import com.example.a79273.shandianban.R;
import com.example.a79273.shandianban.ShopingCarActivity;
import com.example.a79273.shandianban.adapter.YouHuoParticularsAdapter;
import com.example.a79273.shandianban.config.NetconfigYouHuo;
import com.example.a79273.shandianban.db.Collect;
import com.example.a79273.shandianban.db.ShopingCar;
import com.example.a79273.shandianban.model.YouHuoProducBean;
import com.example.a79273.shandianban.model.YouHuoProductTopImgsBean;
import com.example.a79273.shandianban.view.MyTextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.hintview.ColorPointHintView;
import com.squareup.picasso.Picasso;

import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by lenovo on 2016/8/30.
 */
public class ParticularsFragment extends Fragment implements View.OnClickListener {
    private View view;
    private String mPath;
    private String mProid;
    private String mTopImgsPath;
    private RollPagerView mRollPagerView;
    private TextView mTextViewPrice,mTextViewColor,mTextViewSize,mTextViewCount,mTextViewName;
    private MyTextView mMyTextViewPrice;
    private RelativeLayout mRelativeLayout;//颜色尺码...的item
    private WebView mWebView;
    private String mWebViewPath;
    private RequestParams mParams;
    private RequestParams mParamsTwo;
    private List<YouHuoProductTopImgsBean.DataBean.ListBean> mData;
    private YouHuoParticularsAdapter mAdapter;
    //是否登录
    private boolean mLoginFlag = true;
    private String mUserName = "tanganna";//用户名
    private DbManager mDb;//数据库
    private ImageView mImageViewCollect,mImageViewCar;//收藏
    private AlertDialog.Builder mBuilder;
    private TextView mTextViewShopingCar,mTextViewBuy;
    private String price;
    private String name;
    private View mViewPopupwindow;
    private TextView mTextViewPopupwindow;
    private PopupWindow mPopupWindow;
    private TextView mTextViewPopPrice,mTextViewPopName,mTextViewPopColor02,mTextViewPopSize02;
    private TextView mTextViewPopColor,mTextViewPopSize,mTextViewPopCount;
    private ImageView mImageViewPopSub,mImageViewPopAdd, mImageViewPopProImg;
    private LinearLayout mLinearLayoutColors;//颜色
    private Button mButtonPopOK;
    private String mImgPath;
    private TextView mTextViewCarCount;
    private int mShopingCarCounts;//购物车里商品的数量
    private boolean mIsShopingCar;//用于判断是加入购物车还是立即购买的标记 false:加入购物车 true:立即购买
    private String mPopShopCounts;//popupwindow里商品数量的值
    private String[] mProductColors;
    private String wara_id;
    private LinearLayout.LayoutParams mTextParams;
    private String mProColor;
    private String mProSize;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
       view = inflater.inflate(R.layout.fragment_particulars,null);
        initView();
        initData();
        setData();
        setListener();
        return view;
    }

    private void setListener() {
        mImageViewCollect.setOnClickListener(this);
        mTextViewShopingCar.setOnClickListener(this);
        mTextViewBuy.setOnClickListener(this);
        mTextViewPopupwindow.setOnClickListener(this);
        mImageViewCar.setOnClickListener(this);
        mRelativeLayout.setOnClickListener(this);
        mImageViewPopSub.setOnClickListener(this);
        mImageViewPopAdd.setOnClickListener(this);
        mButtonPopOK.setOnClickListener(this);
    }

    private void setData() {
        //mRollPagerView.setHintView(new IconHintView(getActivity(), R.mipmap.designer_icon03, R.mipmap.designer_icon04));
        mRollPagerView.setHintView(new ColorPointHintView(getActivity(), Color.BLACK, Color.WHITE));
        mRollPagerView.setAdapter(mAdapter);

        //设置WebView
        mWebView.setWebViewClient(new WebViewClient());
        mWebView.setWebChromeClient(new WebChromeClient());



    }

    private void initData() {
        //获取传过来的地址
        mPath = getArguments().getString("path");
        mProid = getArguments().getString("proid");
        mData = new ArrayList<>();
        mAdapter = new YouHuoParticularsAdapter(mData);
        //-------------------数据库----------------
        DbManager.DaoConfig config = new DbManager.DaoConfig();
        mDb = x.getDb(config);
        selectDB();
        mTextParams = new LinearLayout.LayoutParams(120, 80);//动态创建的TextView的params
        mTextParams.setMargins(10,0,10,10);



        mParams = new RequestParams(mPath);
        //获取RollPagerView里的图片的地址
        x.http().get(mParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if(!TextUtils.isEmpty(result)) {
                    Type listType = new TypeToken<LinkedList<YouHuoProducBean>>(){}.getType();
                    Gson gson = new Gson();
                    LinkedList<YouHuoProducBean> resources = gson.fromJson(result, listType);
                    YouHuoProducBean youHuoProducBean = resources.get(0);
                    YouHuoProducBean.DataBean.MallDetailsBean mallDetails = youHuoProducBean.getData().getMallDetails();
                    mWebViewPath = mallDetails.getDetail();
                    mWebView.loadDataWithBaseURL(null,mWebViewPath,"text/html","UTF-8",null);
                    //设置TextView的数据
                    String priceTemp = mallDetails.getPrice();
                    price = priceTemp.substring(0, (priceTemp.indexOf(".") + 3));
                    mTextViewPrice.setText(price);
                    mMyTextViewPrice.setText("￥"+price);
                    wara_id = mallDetails.getWara_id();
                    //注意转义字符
                    mProductColors = wara_id.split("\\|");
                    if(mProductColors != null && mProductColors.length>0) {
                        mTextViewColor.setText(mProductColors[0]);
                        mTextViewPopColor02.setText(mProductColors[0]);
                        for (int i = 0; i < mProductColors.length; i++) {
                            final TextView textView = new TextView(getActivity());
                            textView.setText(mProductColors[i]);
                            textView.setTextSize(14f);//设置字体大小
                            textView.setTextColor(getResources().getColor(R.color.tablayoutTextColor));//设置字体颜色
                            textView.setBackgroundColor(getResources().getColor(R.color.colorProductInfoTabtext));//设置背景颜色
                            textView.setGravity(Gravity.CENTER);
                            textView.setPadding(0,0,0,10);
                            textView.setLayoutParams(mTextParams);
                            mLinearLayoutColors.addView(textView);
                            textView.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    mTextViewPopColor02.setText(textView.getText().toString());
                                }
                            });
                        }
                    }else {
                        mTextViewColor.setText(wara_id);
                        mTextViewPopColor02.setText(wara_id);
                        //只有一个颜色时候
                        final TextView textView = new TextView(getActivity());
                        textView.setText(wara_id);
                        textView.setTextSize(14f);//设置字体大小
                        textView.setTextColor(getResources().getColor(R.color.tablayoutTextColor));//设置字体颜色
                        textView.setBackgroundColor(getResources().getColor(R.color.colorProductInfoTabtext));//设置背景颜色
                        textView.setLayoutParams(mTextParams);
                        mLinearLayoutColors.addView(textView);
                        textView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mTextViewPopColor02.setText(textView.getText().toString());
                            }
                        });

                    }
                    String spu_id = mallDetails.getSpu_id();
                    mTextViewSize.setText(spu_id);
                    name = mallDetails.getName();
                    mTextViewName.setText(name);
                    //设置popupwindow里的数据
                    mTextViewPopName.setText(name);
                   // mTextViewPopColor.setText(wara_id);
                    mTextViewPopSize.setText(spu_id);
                    mTextViewPopSize02.setText(spu_id);
                    mTextViewPopPrice.setText(price);
                    mImgPath = NetconfigYouHuo.PIN_JIE+mallDetails.getPic();
                    Picasso.with(getActivity()).load(mImgPath).into(mImageViewPopProImg);

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(getActivity(), "网络出小差啦...", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

        //获取商品详情上面viewPager里的图片地址
        mTopImgsPath = NetconfigYouHuo.PRODUCT_TOP_PIC+mProid+"/";
        mParamsTwo = new RequestParams(mTopImgsPath);
        x.http().get(mParamsTwo, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if(!TextUtils.isEmpty(result)) {
                    Type listType = new TypeToken<LinkedList<YouHuoProductTopImgsBean>>(){}.getType();
                    Gson gson = new Gson();
                    LinkedList<YouHuoProductTopImgsBean> resources = gson.fromJson(result, listType);
                    List<YouHuoProductTopImgsBean.DataBean.ListBean> list = resources.get(0).getData().getList();
                    mData.addAll(list);
                    mAdapter.notifyDataSetChanged();

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
        //对话框
        mBuilder = new AlertDialog.Builder(getActivity());
        mBuilder.setTitle("提示").setMessage("您还没有登录,是否登录?").setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            startActivity(new Intent(getActivity(),LoginActivity.class));//跳转登录页面
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });

        //----------------------popupwindow-------------------
        mPopupWindow = new PopupWindow(mViewPopupwindow, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT,true);
        //设置弹出窗体的背景
        mPopupWindow.setBackgroundDrawable(new ColorDrawable(0xb0000000));
        // 设置外部可点击
        mPopupWindow.setOutsideTouchable(true);
        // 设置弹出窗体可点击
        mPopupWindow.setFocusable(true);
        //设置设置弹出窗体显示时的动画，从底部向上弹出
        mPopupWindow.setAnimationStyle(R.style.shangping_info_popwindow);
    }

    private void initView() {
        mRollPagerView = (RollPagerView) view.findViewById(R.id.rpv_particulars_body);
        mTextViewPrice = (TextView) view.findViewById(R.id.tv_particulars_price);
        mTextViewColor = (TextView) view.findViewById(R.id.tv_particulars_color);
        mTextViewSize = (TextView) view.findViewById(R.id.tv_particulars_size);
        mTextViewCount = (TextView) view.findViewById(R.id.tv_particulars_count);
        mRelativeLayout = (RelativeLayout) view.findViewById(R.id.rl_particulars_layout);
        mWebView = (WebView) view.findViewById(R.id.wv_particulars_webview);
        mTextViewName = (TextView) view.findViewById(R.id.tv_particulars_name);
        mImageViewCollect = (ImageView) view.findViewById(R.id.iv_particulars_collect);
        mTextViewShopingCar = (TextView) view.findViewById(R.id.tv_particulars_addshopcar);
        mTextViewBuy = (TextView) view.findViewById(R.id.tv_particulars_buy);
        mMyTextViewPrice = (MyTextView) view.findViewById(R.id.mtv_tv_particulars_price);
        mImageViewCar = (ImageView) view.findViewById(R.id.iv_particulars_shopingcar);
        mTextViewCarCount = (TextView) view.findViewById(R.id.iv_particulars_carcount);//购物车里产品的数量
        //popupwindow的布局
        mViewPopupwindow = LayoutInflater.from(getActivity()).inflate(R.layout.youhuo_popupwindow,null);
        mTextViewPopupwindow = (TextView) mViewPopupwindow.findViewById(R.id.tv_popwindow_bg);
        mTextViewPopPrice = (TextView) mViewPopupwindow.findViewById(R.id.tv_popwindow_price);
        mTextViewPopName = (TextView) mViewPopupwindow.findViewById(R.id.tv_popwindow_name);
        mTextViewPopColor02 = (TextView) mViewPopupwindow.findViewById(R.id.tv_popwindow_color02);
        mTextViewPopSize02 = (TextView) mViewPopupwindow.findViewById(R.id.tv_popwindow_size02);
       // mTextViewPopColor = (TextView) mViewPopupwindow.findViewById(R.id.tv_popwindow_color);
        mTextViewPopSize = (TextView) mViewPopupwindow.findViewById(R.id.tv_popwindow_size);
        mTextViewPopCount = (TextView) mViewPopupwindow.findViewById(R.id.tv_popwindow_count);
        mImageViewPopSub = (ImageView) mViewPopupwindow.findViewById(R.id.iv_popwindow_sub);
        mImageViewPopAdd = (ImageView) mViewPopupwindow.findViewById(R.id.iv_popwindow_add);
        mImageViewPopProImg = (ImageView) mViewPopupwindow.findViewById(R.id.iv_popwindow_img);
        mButtonPopOK = (Button) mViewPopupwindow.findViewById(R.id.bt_popupwindow_ok);
        mLinearLayoutColors = (LinearLayout) mViewPopupwindow.findViewById(R.id.ll_popwindow_colors);
    }

    //所有点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case  R.id.iv_particulars_collect://收藏
                if(mLoginFlag) {//已登录  把产品的地址存到数据库
                    Collect collect = new Collect();
                    collect.setUserName(mUserName);
                    collect.setProductPath(mPath);
                    try {
                        mDb.save(collect);
                        Toast.makeText(getActivity(), "收藏成功", Toast.LENGTH_SHORT).show();
                    } catch (DbException e) {
                        e.printStackTrace();
                    }

                }else{//未登录  对话框提示登录
                    mBuilder.create().show();
                }
                break;
            case R.id.tv_particulars_addshopcar://加入购物车
                mIsShopingCar=false;
                if(mLoginFlag) {//已登录  弹出popupwindow
                    mPopupWindow.showAtLocation(view,Gravity.BOTTOM,0,0);

                }else{//未登录  对话框提示登录
                    mBuilder.create().show();
                }
                break;
            case R.id.tv_particulars_buy://立即购买
                mIsShopingCar = true;
                if(mLoginFlag) {//已登录
                    mPopupWindow.showAtLocation(view,Gravity.BOTTOM,0,0);
                }else{//未登录  对话框提示登录
                    mBuilder.create().show();
                }
                break;
            case R.id.iv_particulars_shopingcar://跳转购物车
                if(mLoginFlag) {//已登录
                    startActivity(new Intent(getActivity(),ShopingCarActivity.class));
                }else{//未登录  对话框提示登录
                    mBuilder.create().show();
                }
                break;
            case R.id.tv_popwindow_bg:
                mPopupWindow.dismiss();
                break;
            case R.id.rl_particulars_layout:
                mPopupWindow.showAtLocation(view,Gravity.BOTTOM,0,0);
                break;
            case R.id.iv_popwindow_sub://数量减少
                mPopShopCounts = mTextViewPopCount.getText().toString();
                if("1".equals(mPopShopCounts)) {//如果是1的话不做操作
                    Toast.makeText(getActivity(), "已经是最少了,不能再少了", Toast.LENGTH_SHORT).show();
                }else {
                    mTextViewPopCount.setText((Integer.parseInt(mPopShopCounts)-1)+"");//数量值减1
                }
                break;
            case R.id.iv_popwindow_add://数量增加
                mPopShopCounts = mTextViewPopCount.getText().toString();//先获取值
                mTextViewPopCount.setText((Integer.parseInt(mPopShopCounts)+1)+"");//数量值加1
                break;
            case R.id.bt_popupwindow_ok://加入购物车或者立即购买
                if(mIsShopingCar) {//true :立即购买
                    startActivity(new Intent(getActivity(),OrderActivity.class));
                    mPopupWindow.dismiss();
                }else{//false: 加入购物车
                    //存入数据库
                    mPopShopCounts = mTextViewPopCount.getText().toString();//先获取值
                    //获取商品的颜色
                    mProColor = mTextViewPopColor02.getText().toString();
                    //获取商品的尺码
                    mProSize = mTextViewPopSize02.getText().toString();
                    ShopingCar shopingCar = new ShopingCar();
                    shopingCar.setProductCount(mPopShopCounts);//商品数量
                    shopingCar.setProductPath(mPath);//商品地址
                    shopingCar.setUserName(mUserName);//用户名
                    shopingCar.setProductColor(mProColor);//商品颜色
                    shopingCar.setProductSize(mProSize);//商品尺码
                    shopingCar.setmProid(mProid);//设置商品的mProid
                    try {
                        List<ShopingCar> productpath = mDb.selector(ShopingCar.class).where("productpath", "=", mPath).findAll();
                        if(productpath != null && productpath.size()>0) {//已经加入过了
                            Toast.makeText(getActivity(), "宝贝已经存在了...", Toast.LENGTH_SHORT).show();
                        }else{
                            mDb.save(shopingCar);//存入数据库
                            Toast.makeText(getActivity(), "加入购物车成功!", Toast.LENGTH_SHORT).show();
                        }
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    selectDB();
                    mPopupWindow.dismiss();
                }
                break;
        }
    }
    //查询数据库里面的数据的方法
    public void selectDB(){
        try {
            List<ShopingCar> shopCarProuducts = mDb.selector(ShopingCar.class).where("username", "=", mUserName).findAll();
            if(shopCarProuducts != null && shopCarProuducts.size()>0) {
                mShopingCarCounts = shopCarProuducts.size();//获得当前用户购物车里的商品的数量
                mTextViewCarCount.setVisibility(View.VISIBLE);
                mTextViewCarCount.setText(mShopingCarCounts+"");
            }else {
                mTextViewCarCount.setVisibility(View.INVISIBLE);//数量为零的时候隐藏了
            }

        } catch (DbException e) {
            e.printStackTrace();
        }
    }
}
